<template>
    <media v-model="model" del preview multiple :width="props.width" :height="props.height" @del="del" />
    <view @click="upload" class="btn" :style="{ width: props.width, height: props.height }">
        <wd-icon name="camera" size="26" color="#888" />
    </view>
</template>

<script lang="ts" setup>
const emit = defineEmits(['change'])
const props = defineProps({
    type: { type: [String, Array], default: ['image'] },
    sourceType: { type: [String, Array] as any, default: ['album', 'camera'] },
    num: { type: [String, Number] as any, default: 1 }, // 可上传数量
    width: { type: [String, Number], default: '140rpx' },
    height: { type: [String, Number], default: '140rpx' },
    url: { type: String, default: import.meta.env.VITE_SERVER_BASEURL + '/member/system/upload/single' },
    watermarkText: { type: String, default: '' },
})

const model = defineModel<any>({ default: [] })
if (parseInt(props.num) > 1 && !model.value) model.value = []
function del(index: number) {
    uni.showModal({
        content: '确定删除吗', success(res) {
            if (res.confirm) {
                if (parseInt(props.num) == 1) {
                    model.value = null
                } else {
                    model.value.splice(index, 1)
                }
                emit('change', model.value)
            }
        }
    })
}

function upload() {
    uni.chooseFile({
        mediaType: props.type,
        sourceType: props.sourceType,
        success(chooseRes: any) {
            if (parseInt(props.num) == 1 && model.value && model.value.url) return uni.showToast({ title: '只能上传1个文件', icon: 'none' })
            if (parseInt(props.num) > 1 && (chooseRes.tempFilePaths.length + model.value.length) > parseInt(props.num)) return uni.showToast({ title: '只能上传' + props.num + '个文件', icon: 'none' })
            chooseRes.tempFilePaths.map((filePath, index) => {
                return new Promise((resolve, reject) => {
                    if (props.watermarkText) addWatermark(filePath, resolve, reject);
                    else uploadFile(filePath, resolve, reject)
                });
            })
        }
    })
}

function uploadFile(filePath, resolve, reject) {
    // uni.showLoading({ title: '上传中...', mask: true });
    uni.uploadFile({
        url: props.url,
        filePath: filePath,
        name: 'file',
        success: (res) => {
            // uni.hideLoading();
            try {
                const data = JSON.parse(res.data);

                if (data.code != 200) return uni.showToast({ title: data.message, icon: 'none' })
                if (parseInt(props.num) == 1) model.value = data.data
                else model.value.push(data.data)
                emit('change', model.value)

                resolve(data);
            } catch (e) {
                console.error('解析响应数据失败:', e);
                reject(e);
            }
        },
        fail: (err) => {
            // uni.hideLoading();
            console.error('上传失败:', err);
            reject(err);
        }
    });
}

// 添加水印
function addWatermark(tempFilePath: string, resolve, reject) {
    // 创建一个 Canvas
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    // 创建一个图片对象
    const img = new Image();
    img.onload = () => {

        // 设置Canvas的大小为图片的大小
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0);  // 绘制图片

        // 设置水印样式
        let font_size = 18;
        let fontSize = Math.min(canvas.width / font_size, canvas.height / font_size);
        ctx.font = fontSize + 'px Arial';
        ctx.fillStyle = 'rgba(90, 90, 90, ' + 0.5 + ')';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        // 水印间距
        let xOffset = fontSize * 5.5;
        let yOffset = fontSize * 5;
        // 绘制水印
        for (var y = 0; y < canvas.height; y += yOffset) {
            for (var x = 0; x < canvas.width; x += xOffset) {
                ctx.save();
                ctx.translate(x, y);
                ctx.rotate(-Math.PI / 5);
                ctx.fillText(props.watermarkText, 0, 0);
                ctx.restore();
            }
        }
        uploadFile(canvas.toDataURL('image/png'), resolve, reject)
    };
    img.onerror = (err) => {
        uploadFile(tempFilePath, resolve, reject)
    };
    img.src = tempFilePath;
}
</script>

<style scoped>
.mediaBox {
    position: relative;
    display: inline-block;
    margin-right: 20rpx;
    margin-bottom: 20rpx;
}

.mediaBox .icon {
    position: absolute;
    top: -16rpx;
    right: -16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: white;
    border-radius: 50rpx;
}

.other {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    margin-bottom: 20rpx;
    color: #666;
    word-break: break-all;
}

.other .icon {
    margin-left: 20rpx;
}

.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    margin: 10rpx 10rpx 10rpx 0;
    vertical-align: top;
    background: #f5f5f5;
}
</style>